import Field from '@model/entity/Field';
import { getAsyncCustomerViewInitData, getAsyncProductViewInitData } from '@src/api/InitDataApi'
import * as CustomerApi from '@src/api/CustomerApi';

export function useComplementRelatedFieldDateType (){
  // 检查是否有关联客户字段、补全时间格式信息
  const complementCustomerRelationFieldsDateType = async (fields: Field[], customerId: string) => {
    if(!customerId || !fields.length) return;

    // 看看有没有关联字段
    const relatedCustomerFields = fields.filter(field => field.formType === 'relationCustomer');
    if(!relatedCustomerFields.length) return;

    // 这里查询一下对应客户的fields
    // TODO 这里可以看看能不能换个接口
    const res = await CustomerApi.getCustomerFields({ isFromSetting: false });
    if(!res.succ) return;

    const customerFields: Field[] = res?.data || [];
    relatedCustomerFields.forEach(RF => {
      RF.setting = RF.setting || {};
      const fn = RF.setting?.fieldName || '';
      const f = customerFields.find(CF => CF.fieldName === fn);
      if(f){
        // 这里补全一下时间格式
        RF.setting.dateType = f.setting?.dateType;
      }
    })
  }

  // 检查是否有关联产品字段、补全时间格式信息
  const complementProductRelationFieldsDateType = async (fields: Field[]) => {
    if(!fields.length) return;

    // 看看有没有关联字段
    const relatedProductFields = fields.filter(field => field.formType === 'relationProduct');
    if(!relatedProductFields.length) return;

    // 这里查询一下产品的fields
    const res = await getAsyncProductViewInitData();
    if(!res.succ) return;

    const productFields: Field[] = res?.data?.initJson?.fieldInfo || [];
    relatedProductFields.forEach(RF => {
      RF.setting = RF.setting || {};
      const fn = RF.setting.fieldName;
      const f = productFields.find(CF => CF.fieldName === fn);
      if(f){
        // 这里补全一下时间格式
        RF.setting.dateType = f.setting?.dateType;
      }
    })
  }
  return {
    complementCustomerRelationFieldsDateType,
    complementProductRelationFieldsDateType,
  }
}